module jinji.post.api;

import jinji.common.query,
jinji.post.classify,
jinji.post.cr,
jinji.post.model,
jinji.post.service;

extern (C):

mixin getObject!(LockedPost, "getLockedPost", "获取帖子锁定信息", "帖子锁定信息", "updated_at desc");

/// 批量获取帖子是否被锁定
@"是否被锁定"@type("boolean[]")
@Action void batchGetLocked(ref Request req, @"帖子id"long[] ids) {
	foreach (id; ids) {
		req.send(has!(LockedPost, "pid=", id, " AND created_at<=now() AND updated_at>=now()"));
	}
}

/// 锁定帖子
@"锁定记录id"@type("[number]")
extern (D) @Action void lockPost(ref Request req, @"帖子id"long id,
	@"锁定时长（hnsecs）"long duration, @"备注" string desc = "") {
	req.require(Perm.lockTag);
	req.send(jinji.post.service.lockPost(parseId(id),
			cast(StdTime)duration, req.uid, parseDesc(desc)));
}

mixin getObject!(PostVisibility, "getPostVisibility", "查询帖子可见性", "帖子可见性", "updated_at desc");

/// 添加/修改帖子可见性规则
@Action void setPostVisibility(ref Request req, @"帖子id"long pid, @"用户id"long uid,
	@"是否可见"bool visible, @"持续时间（hnsecs）"long duration = StdTime.zero) {
	import core.time;

	req.require(Perm.post);
	req.modify!PostVisibility(parseId(pid), parseId(uid),
		visible, req.uid, now, now + cast(StdTime)duration);
}

/// 获取帖子的协作用户数
@"协作用户数"@type("[number]")
@Action void getCollaborators(ref Request req, long pid) {
	req.send(query!(count!(ChangeRequest, "DISTINCT creator")
			.where("pid=$1"))(pid).get!long);
}

/// 获取指定用户的帖子数
@"帖子数"@type("[number]")
@Action void getPostCount(ref Request req, @"用户id"long uid = 0) {
	req.send(query!(count!Post.where("creator=$1"))(uid ? uid : req.uid).get!long);
}

/// 获取平均每个帖子的标签数
@"平均每个帖子的标签数"@type("[number]")
@Action void getAvgTagCount(ref Request req) {
	import jinji.tag.model;

	if (const postCount = query!(count!Post).get!long) {
		long tagCount = query!(SB.select!"ifnull(sum(count),0)"
				.from!Tag()).get!long +
			query!(SB.select!"ifnull(sum(delta),0)"
					.from!TagCountDelta()).get!long;
		req.send(tagCount / postCount);
	} else
		req.send(0);
}

/// 获取帖子总日访问量
@"帖子总日访问量"@type("[number]")
@Action void getTotalDailyView(ref Request req) {
	auto q = query!(SB.select!"ifnull(sum(recent_views),0)"
			.from!PostView());
	req.send(q.get!long);
}

/// 发帖
@"帖子id"@type("[number]")
@Action void post(ref Request req, @"链接" string url) {
	req.require(Perm.post);
	req.send(postLink(url, req.uid));
}

/// 清除无标签帖子
@"清除数量"@type("[number]")
@Action void clearUntagged(ref Request req) {
	req.require(Perm.post);
	req.send(clean());
}
